package com.wowangz.cms.systemmanage.email.set.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.FreeMarkerResolve;
import com.wowangz.cms.common.utils.MessageObject;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.EncryptUtil;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.email.set.entity.SystemEmail;
import com.wowangz.cms.systemmanage.email.set.service.SystemEmailService;

import freemarker.template.TemplateException;

@Controller
@Scope("prototype")
public class SystemEmailController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SystemEmailController.class);

	/**
	 * @author HUANGYUAN
	 * @description 删除模板
	 * @param request
	 * @param model
	 * @时间 2015年10月10日 下午4:00:15
	 */
	@RequestMapping("/systemmanage/email/emailSet/deleteEmailSet.json")
	public void deleteEmailSet(HttpServletRequest request, HttpServletResponse response) {
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, true);
		AjaxDataEntity entity = new AjaxDataEntity();
		String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4");
		String id = request.getParameter("id");
		try {
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("statusid", SysConstant.RecordStatus.VALID);
				paramMap.put("id", id);
				SystemEmail emailSet = service.queryEmailSetById(paramMap);
				emailSet.setStatusid(SysConstant.RecordStatus.INVALID);
				emailSet.setModifyuserid(getUserContext().getLoginUser().getId());
				emailSet.setModifytime(new Date());
				service.emailSetDelete(emailSet);
				getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			} else {
				getUserContext().setErrorMessage(errorMessage);
			}
		} catch (Exception e) {
			getUserContext().setErrorMessage(errorMessage);
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @描述：邮件设置列表
	 * @author HUANGYUAN
	 * @TIME:2015年10月9日 下午2:36:41
	 * @return
	 */
	@RequestMapping("/systemmanage/email/emailSet/queryEmailSetList.web")
	public String queryEmailSetList() {

		return "/WEB-INF/jsp/systemmanage/email/emailSet/emailSetList";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/systemmanage/email/emailSet/getEmailSetListJson.json", method = RequestMethod.POST)
	public void getEmailSetListJson(HttpServletRequest request, HttpServletResponse response) {
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = new DataGrid();
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = (Map<String, Object>) ServletUtils.getParametersToHashMap(request);
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			long resultCount = service.queryEmailSetCount(map);
			List<SystemEmail> resultList = service.queryEmailSetPage(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("used", DataTypeConstant.LONG);
			dataStyle.addDepict("templatecontent", DataTypeConstant.STRING);
			dataStyle.addDepict("subject", DataTypeConstant.STRING);
			dataStyle.addDepict("templatecode", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("templatetype", SysConstant.TemplateEmailType.class, "getName", new Class[] { long.class });
			dataStyle.addDepictByFunction("usedname", SysConstant.CommonUsedStatus.class, "getName", new Class[] { long.class });
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @author HUANGYUAN
	 * @description 获得类型的参数值
	 * @param request
	 * @param response
	 * @时间 2015年10月10日 下午4:46:53
	 */
	@RequestMapping("/systemmanage/email/emailSet/getTemplateParamerMap.json")
	public void getTemplateParamerMap(HttpServletRequest request, HttpServletResponse response) {
		String mapJson = "";
		MessageObject message = new MessageObject();
		List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
		try {
			String code = request.getParameter("code");
			Map<String, Object> parameterMap = SysConstant.TemplateEmailType.getParameterMap(code);
			Set<String> sets = parameterMap.keySet();
			Map<String, Object> templateMap = null;
			for (Iterator<String> iterator = sets.iterator(); iterator.hasNext();) {
				templateMap = new HashMap<String, Object>();
				String key = (String) iterator.next();
				templateMap.put("key", key);
				templateMap.put("value", parameterMap.get(key));
				listMaps.add(templateMap);
			}
			message.setObject(listMaps);
			String inforMessage = "success";
			message.setInforMessage(inforMessage );
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			String errorMessage = MessageResourcesUtils.getMessage(request, "systemmanage.sms.alert.error");
			message.setErrorMessage(errorMessage );
		} finally {
			try {
				mapJson = new Gson().toJson(message);
				response.getWriter().write(mapJson);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @author HUANGYUAN
	 * @description 修改邮件模板
	 * @param systemEmail
	 * @param request
	 * @param response
	 * @时间 2015年10月15日 下午12:11:01
	 */
	@RequestMapping(value = "/systemmanage/email/emailSet/saveEmailSet.json", method = RequestMethod.POST)
	public void saveEmailSet(SystemEmail systemEmail, HttpServletRequest request, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, true);
			systemEmail.setInputtime(new Date());
			systemEmail.setInputuserid(getUserContext().getLoginUser().getId());
			systemEmail.setModifytime(new Date());
			systemEmail.setModifyuserid(getUserContext().getLoginUser().getId());
			systemEmail.setStatusid(SysConstant.RecordStatus.VALID);
			systemEmail.setUsed(SysConstant.CommonUsedStatus.STOP);
			service.emailSetInsert(systemEmail);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
		} catch (ServiceException e) {
			e.printStackTrace();
			String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2");
			getUserContext().setErrorMessage(errorMessage);
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 测试方法
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/systemmanage/email/emailSet/sendEmail.json", method = RequestMethod.GET)
	public void sendEmail(HttpServletResponse response, HttpServletRequest request) {
		String email = request.getParameter("email");
		String ids = request.getParameter("ids");
		String[] idStrings = ids.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		map.put("statusid", SysConstant.RecordStatus.VALID);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		for (String id : idStrings) {
			map.put("id", id);
			SystemEmail emailSet = service.queryEmailSetById(map);
			Map<String, String> paMap = service.getMap(emailSet, getUserContext());
			if (emailSet.getUsed() == SysConstant.CommonUsedStatus.STOP) {
				resultMap.put("code", SysConstant.RecordStatus.INVALID);
				resultMap.put("message", "该模板没有启用，无法发送短信");
				break;
			}
			try {
				Map<String, Object> messageMap = new HashMap<String, Object>();
				String content = FreeMarkerResolve.freemarkerProcess(paMap, emailSet.getTemplatecontent());
				messageMap.put("email", email);
				EncryptUtil des1 = new EncryptUtil();// 使用默认密钥
				content = EncryptUtil.toUnicode(content);
				messageMap.put("content", des1.encrypt(content));
				messageMap.put("subject", emailSet.getSubject());
				service.sendEmailData(messageMap);
				resultMap.put("code", SysConstant.RecordStatus.VALID);
				resultMap.put("message", "发送成功");
			} catch (IOException e) {
				resultMap.put("code", SysConstant.RecordStatus.INVALID);
				resultMap.put("message", "发送失败");
				e.printStackTrace();
			} catch (TemplateException e) {
				resultMap.put("code", SysConstant.RecordStatus.INVALID);
				resultMap.put("message", "发送失败");
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			response.getWriter().write(new Gson().toJson(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/systemmanage/email/emailSet/startOrStopTemplate.json")
	public void startOrStopTemplate(HttpServletRequest request, HttpServletResponse response) {
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		String id = request.getParameter("id");
		String used = request.getParameter("used");
		Map<String, Object> messageMap = new HashMap<String, Object>();
		SystemEmail emailSet = new SystemEmail();
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(id)) {
				paramMap.put("statusid", SysConstant.RecordStatus.VALID);
				paramMap.put("id", id);
				emailSet = service.queryEmailSetById(paramMap);
				if (emailSet != null) {
					paramMap.remove("id");
					paramMap.put("used", SysConstant.CommonUsedStatus.START);
					paramMap.put("templatetype", emailSet.getTemplatetype());
					if (StringUtils.isNotEmpty(used)) {
						long count = service.queryEmailSetCount(paramMap);
						if (count > 0 && Long.parseLong(used) == SysConstant.CommonUsedStatus.START) {
							messageMap.put("messagetype", SysConstant.RecordStatus.INVALID);
							messageMap.put("message", MessageResourcesUtils.getMessage(request, "systemmanage.email.alert8"));
						} else {
							messageMap.put("messagetype", SysConstant.RecordStatus.VALID);
							if (emailSet.getUsed() == SysConstant.CommonUsedStatus.START) {
								messageMap.put("message", MessageResourcesUtils.getMessage(request, "systemmanage.sms.alert3"));
								emailSet.setUsed(SysConstant.CommonUsedStatus.STOP);
							} else {
								messageMap.put("message", MessageResourcesUtils.getMessage(request, "systemmanage.sms.alert1"));
								emailSet.setUsed(SysConstant.CommonUsedStatus.START);
							}
							service.emailSetUpdate(emailSet);
						}
					}
				}
			}
		} catch (ServiceException e) {
			messageMap.put("messagetype", SysConstant.RecordStatus.INVALID);
			e.printStackTrace();
			if (emailSet.getUsed() == SysConstant.CommonUsedStatus.START) {
				messageMap.put("message", MessageResourcesUtils.getMessage(request, "systemmanage.sms.alert4"));
			} else {
				messageMap.put("message", MessageResourcesUtils.getMessage(request, "systemmanage.sms.alert2"));
			}
			logger.error(e.getMessage());
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(messageMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @author HUANGYUAN
	 * @description 进入添加模板的页面
	 * @param request
	 * @param model
	 * @return
	 * @时间 2015年10月10日 下午4:47:16
	 */
	@RequestMapping("/systemmanage/email/emailSet/toEmailSetAdd.web")
	public String toEmailSetAdd(HttpServletRequest request, Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		model.addAttribute("templatecode", "TEM" + sdf.format(new Date()));
		return "/WEB-INF/jsp/systemmanage/email/emailSet/emailSetAdd";
	}

	/**
	 * @author HUANGYUAN
	 * @description 模板修改
	 * @param request
	 * @param model
	 * @return
	 * @时间 2015年10月10日 下午4:40:20
	 */
	@RequestMapping("/systemmanage/email/emailSet/toEmailSetEdit.web")
	public String toEmailSetEdit(HttpServletRequest request, Model model) {
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		String id = request.getParameter("id");
		try {
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("statusid", SysConstant.RecordStatus.VALID);
				paramMap.put("id", id);
				SystemEmail emailSet = service.queryEmailSetById(paramMap);
				String name = SysConstant.Templatetype.getName(emailSet.getTemplatetype());
				emailSet.setTemplatetypename(name);
				model.addAttribute("emailSet", emailSet);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/email/emailSet/emailSetUpdate";
	}

	/**
	 * @author HUANGYUAN
	 * @description
	 * @param request
	 * @param model
	 * @return 模板查看
	 * @时间 2015年10月10日 下午4:38:45
	 */
	@RequestMapping("/systemmanage/email/emailSet/toEmailSetView.web")
	public String toEmailSetView(HttpServletRequest request, Model model) {
		SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		String id = request.getParameter("id");
		try {
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("statusid", SysConstant.RecordStatus.VALID);
				paramMap.put("id", id);
				SystemEmail systemEmail = service.queryEmailSetById(paramMap);
				String name = SysConstant.Templatetype.getName(systemEmail.getTemplatetype());
				systemEmail.setTemplatetypename(name);
				// 模板替换
				// Map<String, String> variable = service.getMap(smsSet,
				// getUserContext());
				// String process =
				// FreeMarkerResolve.freemarkerProcess(variable,
				// smsSet.getTemplatecontent());
				// smsSet.setTemplatecontent(process);
				model.addAttribute("emailSet", systemEmail);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/email/emailSet/emailSetView";
	}

	/**
	 * @author HUANGYUAN
	 * @description 保存修改的数据
	 * @param smsSet
	 * @param request
	 * @param response
	 * @时间 2015年10月10日 下午4:46:20
	 */
	@RequestMapping(value = "/systemmanage/email/emailSet/updateEmailSet.json", method = RequestMethod.POST)
	public void updateEmailSet(SystemEmail systemEmail, HttpServletRequest request, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			SystemEmailService service = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, true);
			systemEmail.setInputtime(new Date());
			systemEmail.setInputuserid(getUserContext().getLoginUser().getId());
			systemEmail.setModifytime(new Date());
			systemEmail.setModifyuserid(getUserContext().getLoginUser().getId());
			systemEmail.setStatusid(SysConstant.RecordStatus.VALID);
			systemEmail.setUsed(SysConstant.CommonUsedStatus.STOP);
			service.emailSetUpdate(systemEmail);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
		} catch (ServiceException e) {
			e.printStackTrace();
			String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7");
			getUserContext().setErrorMessage(errorMessage);
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
